package com.leehongrim.platformai.modules.controller;

import com.leehongrim.platformai.request.AiReq;
import com.leehongrim.platformai.request.Result;
import com.leehongrim.tools.http.UrlToFile;
import com.leehongrim.tools.image.ImageStitcher;
import com.leehongrim.tools.pdf.PDFUtils;
import com.leehongrim.tools.reqeust.PdfAIRequest;
import jdk.nashorn.internal.ir.IdentNode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.awt.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

@RestController
@Slf4j
@RequestMapping("/ai/pdf")
public class PdfToolController extends OllamaController{

    @Value("${working.dir:/tmp/}")
    private String workingDir;
    @Value("${working.maxPage:5}")
    private Integer maxPage;

    @PostMapping("/chat")
    @ResponseBody
    public Result chatSend(@RequestBody PdfAIRequest pdfAIRequest) {
        Result result = new Result();
        result.setCode(200);
        try{
            long currentTimeMillis = System.currentTimeMillis();
            String currentWorkingDir = workingDir+currentTimeMillis+"/";
            log.info("currentWorkingDir:{}", currentWorkingDir);

            // 存本地
            String requestUrl = pdfAIRequest.getUrl();
            log.info("requestUrl:{}",requestUrl);

            String imageOutputDir;

            String pdfName = requestUrl.substring(requestUrl.lastIndexOf("/")+1);
            if(pdfName.indexOf("pdf") > 0){
                String pdfWorkPath = currentWorkingDir+requestUrl.substring(requestUrl.lastIndexOf("/")+1);
                File pdfFile = UrlToFile.download(requestUrl, pdfWorkPath);
                if(pdfFile == null || !pdfFile.exists()){
                    log.error("pdf file not found");
                    result.setMessage("pdf file not found");
                    return result;
                }

                // 配置参数
                String outputDir = currentWorkingDir+"pdf_images/"; // 输出图片目录
                String imageFormat = "png"; // 图片格式，支持png、jpg等
                int dpi = 300; // 分辨率，300DPI适合打印，72DPI适合屏幕显示

                List<File> imageUrlList = PDFUtils.convertPdfToImages(pdfFile, outputDir, imageFormat, dpi, maxPage);
                log.info("PDF转换图片完成！");

                imageOutputDir = currentWorkingDir+"result.jpg";

                // 纵向拼接：间距5像素，白色背景，输出为JPG
                ImageStitcher.stitchImages(imageUrlList, ImageStitcher.Direction.VERTICAL, 5, Color.WHITE, imageOutputDir);
                log.info("图片拼接完成; {}", imageOutputDir);
            }else if(pdfName.indexOf("jpg") > 0 || pdfName.indexOf("png") > 0){
                imageOutputDir = requestUrl;
                log.info("jpg or png imageOutputDir={}", imageOutputDir);
            }else {
                log.error("only pdf/jpg/png");
                result.setMessage("only pdf/jpg/png");
                return result;
            }

            Map<String, Object> map = new HashMap<>();
            map.put("url", imageOutputDir);
            List<Map<String, Object>> images = new ArrayList<>();
            images.add(map);

            if(pdfAIRequest.getHintKeys() == null || pdfAIRequest.getHintKeys().isEmpty()){
                AiReq aiReq = new AiReq();
                aiReq.setContent("提取图片原文?");
                aiReq.setImages(images);
                Result conResult = super.chatSend(aiReq);
                conResult.setAiReq(aiReq);
                return conResult;
            }

            AtomicReference<String> content = new AtomicReference<>("");
            pdfAIRequest.getHintKeys().forEach(e -> {
                content.set(content + e + "是什么? ");
            });
            AiReq aiReq2 = new AiReq();
            aiReq2.setContent(content.get());
            aiReq2.setImages(images);
            Result oneResult = super.chatSend(aiReq2);
            oneResult.setAiReq(aiReq2);
            return oneResult;

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        return result;
    }
}
